/*
 *    Copyright (c) 2018-2025, proj All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the proj developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: proj
 */

package com.ykht.proj.common.security.mobile;

import com.ykht.proj.common.core.util.WebUtils;
import com.ykht.proj.common.security.component.ProjPreAuthenticationChecks;
import com.ykht.proj.common.security.service.ProjUserDetailsService;
import lombok.Getter;
import lombok.Setter;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.support.MessageSourceAccessor;
import org.springframework.http.HttpHeaders;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.SpringSecurityMessageSource;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsChecker;

/**
 * @author proj
 * @date 2018/8/5 手机登录校验逻辑 验证码登录、社交登录
 */
@Slf4j
public class MobileAuthenticationProvider implements AuthenticationProvider {

	private MessageSourceAccessor messages = SpringSecurityMessageSource.getAccessor();

	private UserDetailsChecker detailsChecker = new ProjPreAuthenticationChecks();

	@Getter
	@Setter
	private ProjUserDetailsService userDetailsService;

	@Override
	@SneakyThrows
	public Authentication authenticate(Authentication authentication) {
		MobileAuthenticationToken mobileAuthenticationToken = (MobileAuthenticationToken) authentication;

		String clientId = WebUtils.extractClientId(WebUtils.getRequest().getHeader(HttpHeaders.AUTHORIZATION)).orElse(null);
		log.info("客户端id：{}",clientId);

		UserDetails userDetails = null;
		MobileAuthenticationToken authenticationToken = null;
		String principal = null;


		if ("applet".equals(clientId)){

			//小程序登陆
			principal = mobileAuthenticationToken.getPrincipal().toString();
			Object user = userDetailsService.loadUserByApplet(principal);

			if (user == null) {
				log.debug("Authentication failed: no credentials provided");

				//c端是没有用户就会创建用户，所以一旦异常可以返回登录失败，而不是未绑定
				throw new BadCredentialsException(messages
						.getMessage("AbstractUserDetailsAuthenticationProvider.noopBindAccount", "用户登陆失败"));
			}
			/*// 检查账号状态
			detailsChecker.check(userDetails);*/
			authenticationToken = new MobileAuthenticationToken(user, null);

		}else if ("pig".equals(clientId)||"applet_b".equals(clientId)){
			//管理系统登陆

			principal = mobileAuthenticationToken.getPrincipal().toString();
			userDetails = userDetailsService.loadUserBySocial(principal);


			if (userDetails == null) {
				log.debug("Authentication failed: no credentials provided");

				throw new BadCredentialsException(messages
						.getMessage("AbstractUserDetailsAuthenticationProvider.noopBindAccount", "Noop Bind Account"));
			}
			// 检查账号状态
			detailsChecker.check(userDetails);

			authenticationToken = new MobileAuthenticationToken(userDetails, userDetails.getAuthorities());
		}
		authenticationToken.setDetails(mobileAuthenticationToken.getDetails());

		return authenticationToken;
	}

	@Override
	public boolean supports(Class<?> authentication) {
		return MobileAuthenticationToken.class.isAssignableFrom(authentication);
	}

}
